/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sqlserver;

import java.util.ArrayList;
import java.util.List;

import javax.xml.xpath.*;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


/**
 *
 * @author ROMANCE
 */
public class Delete {
    // kiem tra cu phap
	public static boolean validate_syntax_command (String command, String database)
	{
		String[] syntax_arr = command.split(" ");
		int length = syntax_arr.length;
		
		if(length < 3)
			return false;
		
		if (length != 3 && length != 4 && length%2 != 1)
			return false;
		
		String tableName = "";
		switch(length)
		{
			case 3:
				/*
				 * DELETE FROM table_name
				 */ 
				
				
				// kiem tra tu khoa
				if(syntax_arr[0].compareTo("delete") != 0 || syntax_arr[1].compareTo("from") != 0)
					return false;
				
				
				tableName = syntax_arr[2];
				// kiem tra ten table
				// to do
				if (Create.CheckTableExist(database, tableName) == false)
					return false;
				
				break;
				
			case 4:
				/*
				 * DELETE * FROM table_name
				 */
				
				
				// kiem tra tu khoa
				if(syntax_arr[0].compareTo("delete") != 0 || syntax_arr[1].compareTo("*") != 0 || syntax_arr[2].compareTo("from") != 0)
					return false;
				
				
				tableName = syntax_arr[3];
				// kiem tra ten table
				// to do
				if (Create.CheckTableExist(database, tableName) == false)
					return false;
				
				break;
				
			default:
				
				/*
				 * 	DELETE FROM table_name
				 *	WHERE some_column = some_value
				 * 
				 */
				
				// kiem tra tu khoa
				if (syntax_arr[0].compareTo("delete") != 0 || syntax_arr[1].compareTo("from") != 0 || syntax_arr[3].compareTo("where") != 0)
					return false;
				
				
				tableName = syntax_arr[2];
				// kiem tra ten table
				// to do
				if (Create.CheckTableExist(database, tableName) == false)
					return false;
				
				boolean flag = true;
				for(int i = 4; i < length; i++)
				{
					switch(i%4)
					{
						case 0:
							// kiem tra la thuoc tinh cua bang
							// to do
							if (CheckColumn.CheckColumnExist(database, tableName, syntax_arr[i]) == false)
								return false;
							
							flag = false;
							
							break;
							
						case 1:
							// kiem tra la cac toan tu: =, >, <, <>, >=, <=,  /* is, isnot */
							String operator = syntax_arr[i];
							if(operator.compareTo("=") != 0 && operator.compareTo("<") != 0 && operator.compareTo(">") != 0 && operator.compareTo("<>") != 0 && operator.compareTo("<=") != 0 && operator.compareTo(">=") != 0)
								return false;
							
							flag = false;
							
							break;
						
						case 2:
							// kiem tra gia tri
							// to do
							if (Validation.validate_value(syntax_arr[i]) == false)
								return false;
							
							
							Column column = CheckColumn.getColumnByName(database, tableName, syntax_arr[i-2]);							
							if(column.getColumnType().compareTo(Validation.get_type_value(syntax_arr[i])) != 0)
								return false;
							
							flag = true;
							
							break;
							
						case 3:
							// kiem tra lien tu: AND, OR
							if(syntax_arr[i].compareTo("and") != 0 && syntax_arr[i].compareTo("or") != 0)
								return false;
							
							flag = false;
							
							break;
					}
				}
				
				if(flag == false)
					return false;
				
				break;
		}
		
		return true;
	}
	
	

	
	// thuc thi lenh
	public static int execute_syntax_command (String command, String dbName)
	{
		String tableName = "";
		
		ArrayList<String> columns = new ArrayList<String>();
		ArrayList<String> values = new ArrayList<String>();
		ArrayList<String> operators = new ArrayList<String>();
		ArrayList<String> conjunctions = new ArrayList<String>();
		
		String[] syntax_arr = command.split(" ");
		int length = syntax_arr.length;
		
		switch(length)
		{
			case 3:
				/*
				 * DELETE FROM table_name
				 */ 
				
				tableName = syntax_arr[2];
				
				return execute_command(dbName, tableName, null, null, null, null);
				
				//break;
				
			case 4:
				/*
				 * DELETE * FROM table_name
				 */
				
				
				tableName = syntax_arr[3];
				
				return execute_command(dbName, tableName, null, null, null, null);
				
				//break;
				
			default:
				
				/*
				 * 	DELETE FROM table_name
				 *	WHERE some_column = some_value
				 * 
				 */

				
				tableName = syntax_arr[2];

				for(int i = 4; i < length; i++)
				{
					switch(i%4)
					{
						case 0:
							// column name
							columns.add(syntax_arr[i]);
							
							break;
							
						case 1:
							// cac toan tu: =, >, <, <>, >=, <=,  /* is, isnot */
							if(syntax_arr[i].compareTo("<>") == 0)
								syntax_arr[i] = "!=";
							
							operators.add(syntax_arr[i]);
							
							break;
						
						case 2:
							// value
							
							values.add(Validation.clear_value(syntax_arr[i]));
							
							break;
							
						case 3:
							// AND, OR
							conjunctions.add(syntax_arr[i]);
							
							break;
					}
				}
				
				return execute_command(dbName, tableName, columns.toArray(new String[0]), values.toArray(new String[0]), operators.toArray(new String[0]), conjunctions.toArray(new String[0]));
				
				//break;
		}
		
		
		//return execute_command(dbName, tableName, columns, values, operators, conjunctions);
	}
	
	public static int execute_command (String dbName, String tableName, String[] columns, String[] values, String[] operators, String[] conjunctions)
	{
		if(columns == null)
		{
			
			try {
				Document doc = (Document) MetaManipulation.load_doc(dbName, tableName);
				if (doc == null)
					return MetaManipulation.ErrorLoading;
				
				XPath xpath = XPathFactory.newInstance().newXPath();
				// XPath Query for showing all nodes value
				XPathExpression expr = xpath.compile("//table[@name='" + tableName
						+ "']");
				
				Node oldChilds = (Node) expr.evaluate(doc, XPathConstants.NODE);
				
				oldChilds.getParentNode().removeChild(oldChilds);				
				
				MetaManipulation.save_doc(doc, dbName);
				
				return MetaManipulation.Success;
				
			} catch (Exception e) {
				return MetaManipulation.ErrorUnknown;
			}
		}
		else
		{
			if(conjunctions == null)
			{
				Document doc = MetaManipulation.load_doc(dbName, tableName);
				if (doc == null)
					return MetaManipulation.ErrorLoading;
				
				XPath xpath = XPathFactory.newInstance().newXPath();
				XPathExpression expr = null;
				try {
					expr = xpath.compile("//table[@name='"
							+ tableName + "']/row/column[name='" + columns[0] + "' and value" + operators[0] + "'" + values[0] + "']");
				} catch (XPathExpressionException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				NodeList oldChilds = null;
				try {
					oldChilds = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
				} catch (XPathExpressionException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				Node aNode = null;
				int length = oldChilds.getLength();
				for(int i = 0; i < length; i++)
				{
					aNode = oldChilds.item(i);
					
					aNode.getParentNode().getParentNode().removeChild(aNode.getParentNode());
				}
				
				MetaManipulation.save_doc(doc, dbName);
				
				return MetaManipulation.Success;
			}
			else
			{
				Document doc = MetaManipulation.load_doc(dbName, tableName);
				if (doc == null)
					return MetaManipulation.ErrorLoading;
				
				String str_path = "//table[@name='"
					+ tableName + "']/row[";
				
				
				int len = columns.length;
				for(int i = 0; i < len; i++)
				{
					if(i < len - 1)
					{
						str_path += "column[name='" + columns[i] + "' and value" + operators[i] + "'" + values[i] + "']" + " " + conjunctions[i] + " ";
					}
					else
					{
						str_path += "column[name='" + columns[i] + "' and value" + operators[i] + "'" + values[i] + "']" + "]";
						
					}
				}
				
				
				XPath xpath = XPathFactory.newInstance().newXPath();
				XPathExpression expr = null;
				try {
					expr = xpath.compile(str_path);
				} catch (XPathExpressionException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				NodeList oldChilds = null;
				try {
					oldChilds = (NodeList) expr.evaluate(doc, XPathConstants.NODESET);
				} catch (XPathExpressionException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				Node aNode = null;
				int length = oldChilds.getLength();
				for(int i = 0; i < length; i++)
				{
					aNode = oldChilds.item(i);
					
					aNode.getParentNode().removeChild(aNode);
				}
				
				MetaManipulation.save_doc(doc, dbName);
				
				return MetaManipulation.Success;
			}
		}
	}

}
